package com.hfzy.ihk.web.freeswitchManage.controller;

import com.hfzy.ihk.common.util.file.excel.ExcelUtils;
import com.hfzy.ihk.common.util.file.excel.ImportExcelUtil;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.facade.freeswitchManage.entity.BadCustomerPhone;
import com.hfzy.ihk.web.freeswitchManage.biz.BadCustomerPhoneBiz;
import com.hfzy.ihk.web.freeswitchManage.constant.RedisKeys;
import com.hfzy.ihk.web.freeswitchManage.mapper.BadCustomerPhoneMapper;
import com.hfzy.ihk.web.freeswitchManage.vo.BadPhoneImportVo;
import com.hfzy.ihk.web.oauth.client.table.PageTableHandler;
import com.hfzy.ihk.web.oauth.client.table.PageTableRequest;
import com.hfzy.ihk.web.oauth.client.table.PageTableResponse;
import com.hfzy.ihk.web.oauth.client.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by czs on 2019/5/27.
 */
@RestController
@RequestMapping("external/badCustomerPhone")
@Slf4j
public class BadCustomerPhoneController {


    @Autowired
    private BadCustomerPhoneMapper badCustomerPhoneMapper;

    @Autowired
    private BadCustomerPhoneBiz badCustomerPhoneBiz;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 页面
     * @param modelAndView
     * @return
     */
    @RequestMapping("badCustomerPhonePage")
    public ModelAndView badCustomerPhonePage(ModelAndView modelAndView){
        modelAndView.setViewName("page/badCustomerPhone/queryBadCustomerPhone");
        return modelAndView;
    }

    @RequestMapping("addBadCustomerPhonePage")
    public ModelAndView addBadCustomerPhonePage(ModelAndView modelAndView){
        modelAndView.setViewName("page/badCustomerPhone/addBadCustomerPhone");
        return modelAndView;
    }

    @RequestMapping("editBadCustomerPhonePage")
    public ModelAndView editBadCustomerPhonePage(ModelAndView modelAndView,Integer id){
        modelAndView.addObject("id",id);
        BadCustomerPhone badCustomerPhone = badCustomerPhoneMapper.queryById(id);
        modelAndView.addObject("badCustomerPhone",badCustomerPhone);
        modelAndView.setViewName("page/badCustomerPhone/editBadCustomerPhone");
        return modelAndView;
    }


    /**
     * 查询呼叫包
     * @param request
     * @return
     */
    @RequestMapping("queryBadCustomerPhone")
    public PageTableResponse queryBadCustomerPhone(PageTableRequest request) {
        request.setOffset((request.getOffset()-1)*request.getLimit());

        return new PageTableHandler(new PageTableHandler.CountHandler() {

            @Override
            public int count(PageTableRequest request)
            {

                return badCustomerPhoneMapper.count(request.getParams());
            }
        }, new PageTableHandler.ListHandler() {

            @Override
            public List<BadCustomerPhone> list(PageTableRequest request) {



                List<BadCustomerPhone> list = badCustomerPhoneMapper.list(request.getParams(), request.getOffset(), request.getLimit());
                return list;
            }
        }).handle(request);
    }


    @RequestMapping("save")
    public Map<String,Object> save(BadCustomerPhone badCustomerPhone){

        Map<String,Object> map = new HashMap<>();

        try {
            badCustomerPhoneBiz.saveOrUpdate(badCustomerPhone);
            map.put("code",1);
            map.put("msg","保存成功");
        }catch (Exception e){
            log.error(">>保存异常badPhone",e);
            map.put("code",0);
            map.put("msg","保存失败");
        }

        return map;

    }


    @RequestMapping("del")
    public Map<String,Object> del(Integer id){
        Map<String,Object> map = new HashMap<>();

        try {
            BadCustomerPhone badCustomerPhone = badCustomerPhoneMapper.selectById(id);
            badCustomerPhone.setState(0);
            badCustomerPhoneBiz.updateById(badCustomerPhone);
            map.put("code",1);
            map.put("msg","删除成功");
        }catch (Exception e){
            log.error(">>保存异常badPhone",e);
            map.put("code",0);
            map.put("msg","删除失败");
        }
        return map;


    }



    /**
     * 导入客户
     * @param request
     * @param response
     */
    @RequestMapping("exportTemplate")
    public void exportTemplate(HttpServletRequest request, HttpServletResponse response){
        try {
            //excel标题
            String[] title = {"客户号码","来源","备注"};

            String fileName = "封号号码模板.xls";

            //excel文件名
            try {
                fileName = new String(fileName.getBytes("utf8"),"ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                log.error("导出客户模板名称异常：{}",e);
            }

            String[] value1 = {"13418035054","合富置业","客户投诉号码"};
            String[][] values = {value1};

            //创建HSSFWorkbook
            HSSFWorkbook wb = ImportExcelUtil.getHSSFWorkbook("Sheet1", title, values, null);

            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        }catch (Exception e){
            log.error("导出客户模板异常：{}",e);
        }
    }


    /**
     *导入客户信息
     * @return
     */
    @RequestMapping("importExcel")
    public Map<String,String> importExcel(@RequestParam("file") MultipartFile file){
        Map<String,String> map = new HashMap<>();
        try {
            if(file==null){
                map.put("code","-1");
                map.put("msg","文件不能为空");
                return map;
            }
            String fileName = file.getOriginalFilename();
            if (!fileName.matches("^.+\\.(?i)(xlsx)$|^.*\\.(?:xls)$")) {
                map.put("code","-1");
                map.put("msg","文件格式不正确");


                return map;
            }
            FileInputStream is = (FileInputStream) file.getInputStream();

            List<BadPhoneImportVo> list = (List<BadPhoneImportVo>) ImportExcelUtil.importExcel(null,is ,1, 0, BadPhoneImportVo.class);
            if(list==null||list.size()==0){
                map.put("code","-1");
                map.put("msg","文件为空");


                return map;
            }
            int successCount = 0;
            int failCount = 0;
            for(BadPhoneImportVo badPhoneImportVo :list){
                try {
                    BadCustomerPhone badCustomerPhone = new BadCustomerPhone();
                    badCustomerPhone.setBadPhone(badPhoneImportVo.getBadPhone());
                    badCustomerPhone.setRemark(badPhoneImportVo.getRemark());
                    badCustomerPhone.setSource(badPhoneImportVo.getSource());
                    badCustomerPhoneBiz.saveOrUpdate(badCustomerPhone);
                    successCount++;
                }catch (Exception e){
                    failCount++;

                }
            }
            map.put("code","1");
            map.put("msg","导入成功");
            map.put("successCount",String.valueOf(successCount));
            map.put("failCount",String.valueOf(failCount));

        } catch (Exception e) {
            log.error("导入ex 失败",e);
            map.put("code","0");
            map.put("msg","导入失败");
        }
        return map;
    }


    /**
     * 判断某个号码是否在黑名单内
     * @param customerPhone
     * @return
     */
    @RequestMapping("checkBadPhone")
    public Map<String,Object> checkBadPhone(String customerPhone){
        Map<String,Object> map = new HashMap<>();
        if(StringUtil.isEmpty(customerPhone)){
            map.put("code",-1);
            map.put("msg","号码为空");
        }
        try{
            Object state = redisTemplate.opsForHash().get(RedisKeys.BAD_CUSTOMER_PHONE_MAP,customerPhone);
            if(state!=null&&"1".equals(state.toString())){
                map.put("code",1);
                map.put("msg","属于黑名单");
            }else{
                map.put("code",-1);
                map.put("msg","不属于黑名单");
            }

        }catch (Exception e){
            log.error(">>>zy查询黑名单异常",e);
            map.put("code",-1);
            map.put("msg","不属于黑名单");
        }
        return map;
    }

    /**
     * 将数据从之前的redis set 导出来插入数据表中，然后在导入到redis map中
     * @return
     */
    @RequestMapping("initiDataFromRedis")
    public String initiDataFromRedis(){
        Set<String> badCustomerPhones = redisTemplate.opsForSet().members(RedisKeys.BAD_CUSTOMER_PHONE);


        if(badCustomerPhones==null || badCustomerPhones.isEmpty())
            return "获取到空的set";

        log.info(">>>get badCustomerPhones size:{}", badCustomerPhones.size());
        for(String phone:badCustomerPhones){
            if(phone.length()>18)
                continue;
            try {
                BadCustomerPhone badCustomerPhone = new BadCustomerPhone();
                badCustomerPhone.setSource("置业系统");
                badCustomerPhone.setRemark("客户投诉号码");
                badCustomerPhone.setBadPhone(phone);
                badCustomerPhone.setState(1);
                badCustomerPhoneBiz.saveOrUpdate(badCustomerPhone);
            }catch (Exception e){
                log.info(">>初始化黑名单数据生成数据异常",e);
            }

        }
        return "成功";

    }

}
